<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
</head>
<body>
<script>

window.jsTestIsAsync = true;
var mutations;
var div, subDiv;

function testBasic() {
    var observer;

    function start() {
        debug('Testing basic aspects of cross-document observation.');

        mutations = null;
        div = document.createElement('div');
        observer = new MutationObserver(function(mutations) {
            window.mutations = mutations;
        });

        observer.observe(div, {attributes: true});
        var newDoc = document.implementation.createDocument('', '', null);
        newDoc.appendChild(div);
        div.id = 'foo';
        setTimeout(finish, 0);
    }

    function finish() {
        shouldBe('mutations.length', '1');
        shouldBe('mutations[0].type', '"attributes"');
        shouldBe('mutations[0].target', 'div');
        shouldBe('mutations[0].attributeName', '"id"');
        shouldBe('mutations[0].attributeNamespace', 'null');
        observer.disconnect();
        debug('');
        runNextTest();
    }

    start();
}

function testSubtree() {
    var observer;

    function start() {
        debug('Testing that subtree observation works after node is moved.');

        mutations = null;
        div = document.createElement('div');
        subDiv = div.appendChild(document.createElement('div'));
        observer = new MutationObserver(function(mutations) {
            window.mutations = mutations;
        });

        observer.observe(div, {attributes: true, subtree: true});
        var newDoc = document.implementation.createDocument('', '', null);
        newDoc.appendChild(div);
        subDiv.id = 'foo';
        setTimeout(finish, 0);
    }

    function finish() {
        shouldBe('mutations.length', '1');
        shouldBe('mutations[0].type', '"attributes"');
        shouldBe('mutations[0].target', 'subDiv');
        shouldBe('mutations[0].attributeName', '"id"');
        shouldBe('mutations[0].attributeNamespace', 'null');
        observer.disconnect();
        debug('');
        runNextTest();
    }

    start();
}

var tests = [testBasic, testSubtree];
var testIndex = 0;

function runNextTest() {
    if (testIndex < tests.length)
        tests[testIndex++]();
    else
        finishJSTest();
}

description('Test that MutationObservers move correctly across documents');

runNextTest();

</script>
</body>
</html>
